using Godot;
using Godot.Collections;
using System;

public partial class UiTask : Ui
{
	public Dictionary<string,Variant> tasks;
	public Array<string> ParentTasksName;
	public string ChosenTask = "";
	public Label Description;
	public Button FollowButton;
	private Player _player;
	private TaskManager _taskManager;
	private GridContainer TasksGrid;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		var Game = GetNode<Game>("/root/Game");
		_player = Game.get_player();
		_taskManager = _player.GetNode<TaskManager>("%TaskManager");
		TasksGrid = GetNode<GridContainer>("%TasksGrid");
		Description = GetNode<Label>("%Description");
		FollowButton = GetNode<Button>("%FollowButton");
		FollowButton.ButtonUp += ChangeFollow;
		MessageManager messageManager = Game.get_message_manager();
		messageManager.ChooseTask += ShowDescription;
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

    public override void enter()
    {
        base.enter();
		TaskBar();
    }

	public override void exit()
	{
		base.exit();
		Description.Text = "";
	}

	public void GetTasksInfo()
	{
	}

	public void TaskBar()
	{
		ClearTaskBar();
		foreach(ParentTask parent in _taskManager.tasksDic.Keys)
		{
			string parentName = parent.name;
			string TaskBarPath = "res://components/task_component/task_bar.tscn";
		
			var Game = GetNode<Game>("/root/Game");

			if(parent.CurrentState == Tasks.State.COMPLETED)
			{continue;}
			TaskBar parentBar = Game.InstantScene(TaskBarPath) as TaskBar;
			TasksGrid.AddChild(parentBar);
			parentBar.Initialize();
			parentBar.SetTaskName(parentName);
			
			Array<Tasks> childrern = _taskManager.tasksDic[parent];
			
			if(childrern.Count != 0)
			{
				parentBar.AddChildTask(childrern);
				
			}
		}
	}

	public void ShowDescription(string taskname, string parent)
	{
		string descriptionText = "";
		ChosenTask = taskname;
		//GD.Print("" + taskname);
		if(parent == "")
		{
			FollowButton.Visible = false;
			Dictionary<string,Variant> parentData = _taskManager.tasksText[taskname].AsGodotDictionary<string,Variant>();
			descriptionText = parentData["description"].ToString();
			
		}
		else
		{
			FollowButton.Visible = true;
			Dictionary<string,Variant> parentData = _taskManager.tasksText[parent].AsGodotDictionary<string,Variant>();
			descriptionText = parentData[taskname].ToString();
			
		}
		Description.Text = descriptionText;
	}

	public void ClearTaskBar()
	{
		foreach(var task in TasksGrid.GetChildren())
		{
			TasksGrid.RemoveChild(task);
		}
	}

	public void ChangeFollow()
	{
		foreach (var child in _taskManager.runningTasks)
		{
			if(child.name == ChosenTask)
			{
				_taskManager.ChangeFollow(child);
				break;
			}
		}
	}

}
